package com.java.util.mvc;

import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MvcDateConverter extends PropertyEditorSupport {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    private String[] patterns = null;

    public MvcDateConverter() {}
    
    public MvcDateConverter(String[] patterns) {
	this.patterns = patterns;
    }

    public void setAsText(String text) throws IllegalArgumentException {
	if (StringUtils.isEmpty(text)) {
	    setValue(null);
	    return;
	}
	Date date = null;
	try {
	    date = DateUtils.parseDate(text, this.patterns);
	} catch (Exception e) {
	    this.logger.error("parseDate error", e);
	}
	setValue(date);
    }

    public String getAsText() {
	Date value = (Date) getValue();
	String strDate = "";
	if (value != null) {
	    SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    formater.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
	    try {
		strDate = formater.format(value);
	    } catch (Exception e) {
		e.printStackTrace();
	    }

	    // strDate = DateUtil.dateToString(value, "yyyy-MM-dd HH:mm:ss");
	}
	return strDate;
    }
}
